<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Pay as LibraryPay;
use app\common\library\Wechat;
use GuzzleHttp\Exception\ClientException;
use think\Db;

/**
 * 支付接口
 * 
 */
class Pay extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 支付
     * @ApiMethod (POST)
     * @param int $id  订单id
     * @param int $pay_type 类型:1=微信小程序支付,2=微信app支付,3=支付宝支付,4=积分支付,5=余额支付
     * @param int $attach  order=商城订单,real=实名订单
     * @param int $code  
     * @param string $paypwd  
     * 
     */
    public function pay()
    {

        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        if (!isset($pay_type)) {
            $this->error('请选择支付方式');
        }
        Db::startTrans();
        try {
            if ($pay_type == 1) {
                $wechat = new Wechat('wxMiniProgram');
                $decryptSession = $wechat->code($code);
                if (!isset($decryptSession['session_key'])) {
                    exception($decryptSession['errmsg']);
                }
                if (empty($decryptSession['openid']) || empty($decryptSession['unionid'])) {
                    exception('code错误,请重试!');
                }
                if (empty($decryptSession['openid'])) {
                    exception('code错误,请重试!');
                }
                $openid = $decryptSession['openid'];
            }
            $data = LibraryPay::pay($id, $attach, $pay_type, $openid ?? '', $paypwd ?? '');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('提交支付失败：' . $e->getMessage());
        }
        $this->success('', $data ?? '');
    }
}
